<template>
  <div class="home">
    <nav-bar></nav-bar>
    <van-tabs v-model="active" swipeable sticky>
      <van-tab :key="index" v-for="(item, index) in categoryList" :title="item.title">
        <van-list
          v-model="item.loading"
          :immediate-check="false"
          :finished="item.finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div class="detail">
            <home-detail
              class="detailItem"
              :key="index1"
              v-for="(item1, index1) in item.List"
              :detailList="item1"
            ></home-detail>
          </div>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import NavBar from '@/components/common/NavBar'
import HomeDetail from '@/components/home/detail'

export default {
  data() {
    return {
      categoryList: [],
      active: 0,
    }
  },
  components: {
    NavBar,
    HomeDetail,
  },
  created() {
    //导航的列表信息
    this.getCategoryList()
  },
  methods: {
    //获取导航的列表信息
    async getCategoryList() {
      const res = await this.$axios.get('/category')
      // console.log(res)
      // this.categoryList = res.data
      this.changeCategory(res.data)
      this.getArticalList()
      // console.log(this.$route)
    },
    changeCategory(data) {
      const categoryList1 = data.map((item, index) => {
        ;(item.List = []), (item.page = 0), (item.pagesize = 10), (item.finished = false), (item.loading = true)
        return item
      })
      this.categoryList = categoryList1
    },
    // 获取文章数据
    async getArticalList() {
      const category = this.categoryItem()
      const res = await this.$axios.get('/detail/' + category._id, {
        params: {
          page: category.page,
          pagesize: category.pagesize,
        },
      })
      // console.log(res)
      category.List.push(...res.data)
      category.loading = false
      if (res.data.length < category.pagesize) {
        category.finished = true
      }
      // console.log(category.finished)
      // category.List = res.data
    },
    //获取每次点击时的分类信息
    categoryItem() {
      const categoryItem = this.categoryList[this.active]
      // console.log(categoryItem)
      return categoryItem
    },
    onLoad() {
      const category = this.categoryItem()
      setTimeout(() => {
        category.page += 1
        this.getArticalList()
      }, 1000)
    },
  },
  watch: {
    active() {
      //每次点击分类则会触发这个函数
      this.getArticalList()
    },
  },
}
</script>

<style lang="stylus" scoped>
.home {
  background-color: #fff;
}

.van-tabs__nav, .van-tabs__nav--line, .van-tabs__nav--complete {
  margin-right: 8.611vw !important;
}

.detail {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.detailItem {
  width: 50%;
}
</style>
